package com.zzuli.yxypre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzuli.yxypre.comment.R;
import com.zzuli.yxypre.entity.*;
import com.zzuli.yxypre.entity.dto.CommentDto;
import com.zzuli.yxypre.mapper.*;
import com.zzuli.yxypre.service.AlbumService;
import com.zzuli.yxypre.utils.JwtUtils;
import com.zzuli.yxypre.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @auther pony
 * @create 2023-04-28 15:25
 */
@Service
public class AlbumServiceImpl extends ServiceImpl<AlbumMapper, Album> implements AlbumService {

    @Autowired
    private AlbumMapper albumMapper;

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ThumbsMapper thumbsMapper;

    @Autowired
    private LoveMapper loveMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    /**
     * 1、根据 专辑（album） id 获取一张 专辑（album） 信息
     * 2、封装 专辑 评论数
     * @param id
     * @return
     */
    @Override
    public R getOneById(Integer id, HttpServletRequest request) {
        // 获取登录用户id
        Integer userId = Integer.valueOf(JwtUtils.getUserIdByJwtToken(request));
        //1、根据专辑id 查询专辑
        LambdaQueryWrapper<Album> qw = new LambdaQueryWrapper<>();
        qw.eq(Album::getAlbumId, id);
        // 状态正常
        qw.eq(Album::getAlbumStatus, 0);
        Album album = albumMapper.selectOne(qw);
        // 判断专辑是否被当前登录用户所喜欢
        LambdaQueryWrapper<Love> loveQw = new LambdaQueryWrapper<>();
        // 歌曲 type 是 1
        loveQw.eq(Love::getType, 2);
        loveQw.eq(Love::getUserId, userId);
        loveQw.eq(Love::getRelevance, album.getAlbumId());
        Love love = loveMapper.selectOne(loveQw);
        if (!Objects.isNull(love)){
            album.setIsLove(1);
        }else {
            album.setIsLove(0);
        }
        if (!Objects.isNull(album)){
            //2、根据专辑id 查询专辑下的所有歌曲
            List<Song> songList = albumMapper.selectSongByAlbumId(id);
            // 判断歌曲是否被当前登录用户所喜欢
            for (Song song : songList) {
                LambdaQueryWrapper<Love> loveQw1 = new LambdaQueryWrapper<>();
                // 歌曲 type 是 1
                loveQw1.eq(Love::getType, 1);
                loveQw1.eq(Love::getUserId, userId);
                loveQw1.eq(Love::getRelevance, song.getSongId());
                Love love1 = loveMapper.selectOne(loveQw1);
                if (!Objects.isNull(love1)){
                    song.setIsLove(1);
                }else {
                    song.setIsLove(0);
                }
            }
            album.setSongList(songList);
            //2-1、根据歌曲id 查询歌手信息和专辑信息
            for (Song song : songList) {
                // 查询歌手
                List<Singer> singerList = songMapper.selectSingerBySongId(song.getSongId());
                song.setSinger(singerList);
                // 查询专辑
                List<Album> albumList = songMapper.selectAlbumBySongId(song.getSongId());
                song.setAlbum(albumList);
            }

            //3、根据专辑id 查询专辑的歌手
            List<Singer> singerList = albumMapper.selectSingerByAlbumId(id);
            album.setSingerList(singerList);

            //4、封装专辑的评论数
            Integer commentCount = albumMapper.selectAlbumCommentCountByAlbumId(id);
            album.setCommentCount(commentCount);

            return R.success().message("根据专辑id，查询专辑信息，成功").data("album", album);
        }
        return R.success().message("根据专辑id，查询专辑信息，失败，系统错误请联系管理员").data("album", album);
    }

    /**
     * 获取专辑的分页评论数据
     * @param albumId 专辑id
     * @param pageCurrent 当前页
     * @param pageSize 每页大小
     * @return
     */
    @Override
    public R commentPage(String order, Integer albumId, Integer pageCurrent, Integer pageSize, HttpServletRequest request) {
        // 获取登录用户id
        Integer userId = Integer.valueOf(JwtUtils.getUserIdByJwtToken(request));
        // 根据热度降序排序并分页
        // 计算 limit 参数1
        Integer limit1 = (pageCurrent - 1) * pageSize;
        List<Comment> commentList = null;
        if ("hot".equals(order)){
            commentList = commentMapper.commentHotDesc(albumId, 2, 1, limit1, pageSize);
        }else if("time".equals(order)){
            commentList = commentMapper.commentTimeDesc(albumId, 2, 1, limit1, pageSize);
        }
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.eq(Comment::getTableType,2);
        qw.eq(Comment::getRelevance, albumId);
        qw.eq(Comment::getType, 1);
        Integer total = commentMapper.selectCount(qw);
        PageInfo pageInfo = new PageInfo(pageCurrent, pageSize, total, commentList);
        for (Comment comment : commentList) {
            comment.setOrder("time");
            // 封装评论人的信息
            User user = userMapper.selectById(comment.getUserId());
            comment.setUser(user);
            // 评论是否被当前登录用户点赞
            LambdaQueryWrapper<Thumbs> thumbsQw = new LambdaQueryWrapper<>();
            thumbsQw.eq(Thumbs::getUserId, userId);
            thumbsQw.eq(Thumbs::getCommentId, comment.getId());
            Thumbs thumbsSelectResult = thumbsMapper.selectOne(thumbsQw);
            if (!Objects.isNull(thumbsSelectResult)){
                comment.setIsThumbs(1);
            }else {
                comment.setIsThumbs(0);
            }
            // 评论总的点赞数
            LambdaQueryWrapper<Thumbs> thumbsQw1 = new LambdaQueryWrapper<>();
            thumbsQw1.eq(Thumbs::getCommentId, comment.getId());
            comment.setThumbsCount(thumbsMapper.selectCount(thumbsQw1));

            // 封装评论的回复
            // 根据评论 id 查询评论的回复
            LambdaQueryWrapper<Comment> replyQw = new LambdaQueryWrapper<>();
            replyQw.eq(Comment::getTableType, 2);
            replyQw.eq(Comment::getRelevance, comment.getId());
            List<Comment> replyList = commentMapper.selectList(replyQw);
            // 封装评论回复数
            comment.setCommentCount(replyList.size());
            // 回复的回复
            for (Comment reply : replyList) {
                // 封装评论的回复的回复人信息
                User replyer = userMapper.selectById(reply.getUserId());
                reply.setUser(replyer);

                // 评论是否被当前登录用户点赞
                LambdaQueryWrapper<Thumbs> replyThumbsQw = new LambdaQueryWrapper<>();
                replyThumbsQw.eq(Thumbs::getUserId, userId);
                replyThumbsQw.eq(Thumbs::getCommentId, reply.getId());
                Thumbs thumbsResult = thumbsMapper.selectOne(replyThumbsQw);
                if (!Objects.isNull(thumbsResult)){
                    reply.setIsThumbs(1);
                }else {
                    reply.setIsThumbs(0);
                }
                // 评论总的点赞数
                LambdaQueryWrapper<Thumbs> replyThumbsQw1 = new LambdaQueryWrapper<>();
                replyThumbsQw1.eq(Thumbs::getCommentId, reply.getId());
                reply.setThumbsCount(thumbsMapper.selectCount(replyThumbsQw1));

                // 回复的回复
                if(reply.getTargetId()!=0){
                    // 设置被回复人的信息
                    User targetUser = userMapper.selectById(reply.getTargetId());
                    reply.setTargetUser(targetUser);
                }

            }
            comment.setReply(replyList);
        }
        return R.success().message("专辑分页评论").data("commentPage", pageInfo);
    }

    /**
     * 为专辑，添加评论
     * @param comment 评论信息
     * @param request
     * @return
     */
    @Override
    public R addComment(Comment comment, HttpServletRequest request) {
        // 1、根据 token 获取登录用户的id
        String id = String.valueOf(JwtUtils.getUserIdByJwtToken(request));
        // 2、封装评论信息
        // 评论人id
        comment.setUserId(Integer.valueOf(id));
        // 评论时间
        comment.setTime(new Date());
        // 3、对敏感词进行过滤
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int insertResult = commentMapper.insert(comment);
        if(insertResult==1){
            return R.success().message("专辑评论添加成功");
        }
        return R.error().message("专辑评论添加失败，系统错误请联系管理员！");
    }

    /**
     * 为专辑评论点赞
     * @param commentId 评论id
     * @param flag 1：点赞 0：取消点赞
     * @param request
     * @return
     */
    @Override
    public R thumbs(Integer commentId, Integer flag, HttpServletRequest request) {
        // 1、根据 token 获取登录用户的id
        Integer userId = Integer.valueOf(JwtUtils.getUserIdByJwtToken(request));
        LambdaQueryWrapper<Thumbs> qw = new LambdaQueryWrapper<>();
        qw.eq(Thumbs::getUserId, userId);
        qw.eq(Thumbs::getCommentId, commentId);
        // 取消点赞
        if (flag==0){
            thumbsMapper.delete(qw);
        }else { //点赞
            Thumbs thumbs = new Thumbs();
            thumbs.setUserId(userId);
            thumbs.setCommentId(commentId);
            thumbsMapper.insert(thumbs);
        }
        return R.success().message("点赞获取消点赞成功！");
    }

    /**
     * @param albumId 专辑id
     * @param count 初始加载评论数
     * @param request
     * @return
     */
    @Override
    public R test(int albumId, int count, HttpServletRequest request) {
        // 获取登录用户id
        Integer userId = Integer.valueOf(JwtUtils.getUserIdByJwtToken(request));
        LambdaQueryWrapper<Comment> qw = new LambdaQueryWrapper<>();
        qw.eq(Comment::getRelevance, albumId);
        // 去前 count 条数据
        qw.last("limit "+count);
        List<Comment> commentList = commentMapper.selectList(qw);
        CommentDto commentDto = new CommentDto();
        commentDto.setCommentList(commentList);
        commentDto.setSumCount(commentList.size());
        return R.success().message("专辑分页评论").data("commentDto", commentDto);
    }
}
